﻿using System;
using System.Windows.Input;

namespace BreathingEffectDemo
{
    // RelayCommand 实现
    public class RelayCommand : ICommand
    {
        private readonly Action _execute;
        private readonly Func<bool> _canExecute;

        // 构造函数，接受执行逻辑和判断是否可以执行的条件
        public RelayCommand(Action execute) : this(execute, null) { }

        public RelayCommand(Action execute, Func<bool> canExecute)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
            _canExecute = canExecute;
        }

        // CanExecuteChanged 事件，每当 CanExecute 返回值可能改变时，需要通知 UI 更新
        public event EventHandler CanExecuteChanged
        {
            add => CommandManager.RequerySuggested += value;
            remove => CommandManager.RequerySuggested -= value;
        }

        // 判断命令是否可以执行
        public bool CanExecute(object parameter)
        {
            return _canExecute == null || _canExecute();
        }

        // 执行命令
        public void Execute(object parameter)
        {
            _execute();
        }

        // 通知命令是否可执行已更改
        public void RaiseCanExecuteChanged()
        {
            CommandManager.InvalidateRequerySuggested();
        }
    }
}
